const http = require('http')
const path = require('path')
const fs = require('fs')
const qs = require("querystring")

const app = http.createServer()

app.on('request', (req, res) => {
  /* 步骤分析
  1、定义请求地址  url:/api/city
  2、传递参数 pname  字符串
  3、服务器需要获取pname  qs
  4、读取对应城市的数据并返回
  */
  // console.log(req.url);
  if (req.url.split('?')[0] == '/api/city') {
    /* 获取参数 /api/city?pname=%E6%B9%96%E5%8C%97%E7%9C%81 */
    var { pname } = qs.parse(req.url.split('?')[1])  //pname=%E6%B9%96%E5%8C%97%E7%9C%81=>} {pname:''}
    // console.log(pname);
    fs.readFile(path.join(__dirname, './city.json'), (err, data) => {
      console.log(JSON.parse(data.toString())[pname]);
      res.end(JSON.stringify(JSON.parse(data.toString())[pname]))
    })
  } else {
    res.end('我是city')
  }
})

app.listen('8848', () => {
  console.log('服务器开起了， http://127.0.0.1:8848');
})